package com.czxy.zuul;

import com.czxy.auth.entity.UserInfo;
import com.czxy.auth.util.JwtUtils;
import com.czxy.config.JwtProperties;
import com.czxy.config.PathProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Liuyunqin 17674029449@163.com
 * @date 2018/12/18 15:51
 */
public class AuthFilter2 extends ZuulFilter {

    @Autowired
    private PathProperties pathProperties;

    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public String filterType() {
        return null;
    }


    /**
     * 执行顺序，数值越小，越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行核心业务run方法
     * @return true 一定执行run方法，false:一定不执行run方法
     * @describe 在这个方法中判断路径是否在白名单中，
     *         如果在：直接return false
     *         如果不在：返回true，执行run方法
     */
    @Override
    public boolean shouldFilter() {
        //1. 获取url
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        //2. 调用方法,返回结果
        return isAllowPath(requestURI);
    }


    public boolean isAllowPath(String url){
        //1. 定义一个变量，存储结果
        //1.1 默认url不在集合中，需要拦截
        boolean flag = true;
        //2. 遍历集合，判断url是否包含在其中
        List<String> allowPaths = pathProperties.getAllowPaths();
        //2.1 判断
        for (String path : allowPaths) {
            if (url.indexOf(path)!=-1) {
                flag = false;
                break;
            }
        }
        //3. 返回结果
        return flag;
    }


    @Override
    public Object run() throws ZuulException {
        //1. 获取request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //3.2 需要拦截,不放行
        //4. 获取token
        String token = request.getHeader("authorization");
        //4.1 token 存在解析
        if (token!=null){
            //5. token解析正确，放行
            try {
                UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
                //5.1 不抛出异常，就是解析成功，放行
                return null;
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        //4.2 如果token不存在，报错
        //token解析失败，报错
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        return null;
    }
}
